const api = require('../../utils/api.js');
const area_picker = require('../../area-picker/area-picker.js');
const app = getApp();

Page({
  data: {
    name: '',
    mobile: '',
    detail: '',
    district: null,
    house_num: '',
    longitude: '',
    latitude: '',
    isDefault: false,
    addressList: [],
    imgUrl: app.imgUrl,
  },

  onLoad(options) {
    let opts = options || {};
    app.pageOnLoad(this);
    let that = this;
    let { address_switch, dispatch_type, id } = opts;
    app.loadCurrencyUnit().then(res => {
      that.setData({
        currency: res.currency,
      });
    });
    app.loadShopSetting().then(res => {
      that.setData({
        check_mobile: res.check_mobile,
      });
    });
    let phone = wx.getSystemInfoSync();  //调用方法获取机型
    let phoneType;
    if (phone.platform == 'ios') {
      phoneType = true;
    } else if (phone.platform == 'android') {
      phoneType = false;
    }
    that.setData({
      address_switch: address_switch || '',
      dispatch_type: dispatch_type || '',
      address_id: id || '',
      opts,
      phoneType,
    });
    that.getDistrictData(function(data) {
      area_picker.init({
        page: that,
        data: data,
      });
    });
    opts.addrInfo &&
      that.wechatAddress(JSON.parse(decodeURIComponent(opts.addrInfo)));
    if (options.address_info) {
      wx.showLoading({
        title: '正在加载',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.user.address_brain,
        data: {
          address_info: decodeURIComponent(options.address_info),
        },
        success: function(res) {
          wx.hideLoading();
          if (res.code === 0) {
            let resp = res.data;
            let { address_switch, dispatch_type } = that.data;
            if (Number(address_switch) === 0) {
              if (Number(dispatch_type) === 1) {
                that.setData({
                  house_num: resp.house_num,
                });
              } else {
                that.setData({
                  detail: resp.house_num,
                });
              }
              that.setData({
                district: resp.district,
              });
            } else {
              that.setData({
                detail:
                  resp.district.province.name +
                  resp.district.city.name +
                  resp.district.district.name +
                  resp.house_num,
              });
            }
            that.setData({
              name: resp.name,
              mobile: resp.mobile,
            });
          }
        },
      });
    }
    if (options.id) {
      wx.showLoading({
        title: '正在加载',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.user.address_detail,
        data: {
          id: options.id,
        },
        success: function(res) {
          wx.hideLoading();
          if (res.code === 0) {
            that.setData(res.data);
          }
        },
      });
    }
    this.checkDefaultAddrerss();
  },

  getDistrictData(cb) {
    let district = wx.getStorageSync('district');
    if (!district || district.length == 0) {
      wx.showLoading({
        title: '正在加载',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.default.district,
        success: function(res) {
          wx.hideLoading();
          if (res.code === 0) {
            district = res.data;
            wx.setStorageSync('district', district);
            cb(district);
          }
        },
      });
      return;
    }
    cb(district);
  },

  onAreaPickerConfirm(e) {
    this.setData({
      district: {
        province: {
          id: e[0].id,
          name: e[0].name,
        },
        city: {
          id: e[1].id,
          name: e[1].name,
        },
        district: {
          id: e[2].id,
          name: e[2].name,
        },
      },
    });
  },

  chooseLocation() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          wx.chooseLocation({
            success: function(res) {
              that.setData({
                location: res.address,
                detail: res.name,
                latitude: res.latitude,
                longitude: res.longitude,
              });
            },
          });
        } else if (res.authSetting['scope.userLocation'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          wx.chooseLocation({
            success: function(res) {
              that.setData({
                location: res.address,
                detail: res.name,
                latitude: res.latitude,
                longitude: res.longitude,
              });
            },
          });
        }
      },
    });
  },

  saveAddress() {
    let _this = this;
    let { check_mobile, mobile, name, address_switch, district, isDefault, currency, address_id,
      detail, location, house_num, longitude, latitude,} = _this.data;
    if (!name) {
      wx.showToast({
        icon: 'none',
        title: '请填写姓名',
      });
      return false;
    }
    if (Number(check_mobile) === 1) {
      if (currency === 'CNY') {
        let myreg = /^1\d{10}$/;
        let myreg2 = app.util.phoneExp.landline;
        if (!myreg.test(mobile) && !myreg2.test(mobile)) {
          wx.showToast({
            icon: 'none',
            title: '联系方式格式不正确',
          });
          return false;
        }
      } else {
        let myreg3 = app.util.phoneExp.canadaPhone;
        if (!myreg3.test(mobile)) {
          wx.showToast({
            icon: 'none',
            title: '联系方式格式不正确',
          });
          return false;
        }
      }
    }

    if (Number(address_switch) === 0) {
      if (!district) {
        district = {
          province: {
            id: '',
          },
          city: {
            id: '',
          },
          district: {
            id: '',
          },
        };
        wx.showToast({
          icon: 'none',
          title: '请选择所在地区',
        });
        return false;
      } else {
        // let location = _this.data.location;
        // let _city = district.city.name;
        // let _area = district.district.name;
        // let addrStr =  _city + _area;
        // if (location && location.indexOf(addrStr) >= 0) {
        //   console.log(true);
        // } else {
        //   wx.showToast({
        //     title: '收货地址与所在地区不匹配，请重新选择',
        //     icon: 'none',
        //   });
        //   return;
        // }
      }
    }
    if (!detail) {
      wx.showToast({
        icon: 'none',
        title: '请选择收货地址',
      });
      return false;
    }
    wx.showLoading({
      title: '正在保存',
      mask: true,
    });
    
    const is_default = isDefault ? 1 : 0;

    app.ws_micro_shoprequest({
      url: api.user.address_save,
      method: 'POST',
      data: {
        address_id,
        name,
        mobile,
        province_id: (district && district.province.id) || '',
        city_id: (district && district.city.id) || '',
        district_id: (district && district.district.id) || '',
        detail,
        location,
        house_num,
        longitude,
        latitude,
        is_default,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          _this.checkDefaultAddrerss();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack();
              }
            },
          });
        }
        if (res.code === 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      complete: res => {
        // _this.upDateDefaultAddressInfo();
      },
    });
  },

  getHouseNumber(e) {
    let value = e.detail.value.trim();
    this.setData({
      house_num: value,
    });
  },

  inputBlur(e) {
    let name = e.currentTarget.dataset.name;
    let value = e.detail.value;
    this.setData({
      [name]: value,
    });
  },

  wechatAddress(addrInfo) {
    let that = this;
    wx.showLoading();
    app.ws_micro_shoprequest({
      url: api.user.wechat_district,
      data: {
        national_code: addrInfo.nationalCode,
        province_name: addrInfo.provinceName,
        city_name: addrInfo.cityName,
        county_name: addrInfo.countyName,
      },
      success: function(res) {
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
        that.setData({
          name: addrInfo.userName || '',
          mobile: addrInfo.telNumber || '',
          detail: addrInfo.detailInfo || '',
          district: res.data.district,
        });
      },
      complete: function() {
        wx.hideLoading();
      },
    });
  },

  checkDefaultAddrerss() {
    const { id = '' } = this.options;
    app.ws_micro_shoprequest({
      url: api.user.address_list,
      success: res => {
        if (res.code === 0 && res.data && res.data.list) {
          const addressList = res.data.list;
          if (addressList.length <= 0) return;

          const item = addressList
            .filter(item => item.id === id)
            .map(item => item.is_default)[0];
          const isDefault = Number(item) === 1 ? true : false;
          this.setData({
            isDefault,
            addressList,
          });
          this.upDateDefaultAddressInfo();
        }
      },
    });
  },

  toggleDefaultAddress(e) {
    this.setData({
      isDefault: e.detail.value,
    });
  },

  upDateDefaultAddressInfo() {
    const { addressList, isDefault } = this.data;
    const { id = '' } = this.options;

    if (isDefault) {
      const defaultAddressInfo = addressList.filter(item => item.id === id)[0];
      wx.setStorageSync('picker_address', defaultAddressInfo);
    } else {
      wx.removeStorageSync('picker_address');
    }
  },
});
